#import "User.h"
#import "DBConnection.h"
#import "StringUtil.h"
#import "UserStore.h"
#import "Statement.h"
#import "GuaziAppDelegate.h"
#import "pinyin.h"

@implementation User

@synthesize userId;
@synthesize name;
@synthesize screenName;
@synthesize location;
@synthesize description;
@synthesize url;
@synthesize followersCount;
//@synthesize profileImageUrl;
@synthesize profileImageUrl_s;
@synthesize profileImageUrl_m;
@synthesize profileImageUrl_b;
@synthesize protected;
@synthesize friendsCount;
@synthesize statusesCount;
@synthesize favoritesCount;
@synthesize following;
@synthesize notifications;

@synthesize provinceCode;
@synthesize provinceName;
@synthesize cityCode;
@synthesize cityName;
@synthesize relation;
@synthesize phone;
@synthesize contact;
@synthesize contactName;
@synthesize remark;
@synthesize state;
@synthesize accountFlag;
@synthesize password;
@synthesize pyLetters;
@synthesize cards;

@synthesize status;

#pragma mark - getters & setters
- (NSString*) remarkName
{
    NSMutableString* s = [NSMutableString string];
    if ( self.screenName && [self.screenName length] > 0 ) {
        [s appendString:self.screenName];
    }
    
    if ( self.remark && [self.remark length] > 0 ) {
        if ( [s length] > 0 ) {
            [s appendFormat:@"[%@]", self.remark];
        }
        else {
            [s appendString:self.remark];
        }
    }
    
    return s;
}


- (BOOL) following
{
    if ( relation == nil ) return NO;
    
    if ( [kUserRelationFollowing compare:relation] == NSOrderedSame || [kUserRelationBoth compare:relation] == NSOrderedSame ) {
        return YES;
    }
    else {
        return NO;
    }
}


- (void) setFollowing:(BOOL)b
{
    if ( b ) {
        //关注
        if ( [kUserRelationNone compare:relation] == NSOrderedSame ) {
            relation = kUserRelationFollowing;
        }
        else if ( [kUserRelationFollower compare:relation] == NSOrderedSame ) {
            relation = kUserRelationBoth;
        }
    }
    else {
        //取消关注
        if ( [kUserRelationFollowing compare:relation] == NSOrderedSame ) {
            relation = kUserRelationNone;
        }
        else if ( [kUserRelationBoth compare:relation] == NSOrderedSame ) {
            relation = kUserRelationFollower;
        }
    }
}


- (NSString*) pyLetters
{
    if ( pyLetters == nil ) {
        NSString* s = self.screenName;
        if ( s==nil || [s length]==0 ) {
            pyLetters = [@"" retain];
        }
        else {
            NSMutableString* py = [NSMutableString stringWithString:@""];
            for ( int i=0; i<[s length]; i++ ) {
                unichar c = [s characterAtIndex:i];
                if ( (c >= '0'&& c<='9') || (c>='a'&&c<='z') || (c>='A'&&c<='Z') ) {
                    [py appendString:[[NSString stringWithFormat:@"%c", c] lowercaseString]];
                }
                else {
                    [py appendString:[NSString stringWithFormat:@"%c", pinyinFirstLetter(c)]];
                }
            }
            pyLetters = [py retain];
        }
    }
    return pyLetters;
}


- (NSString*) toJsonString
{
    NSString* s = [NSString stringWithFormat:@"{userId:'%lld', name:'%@', inContact:'%d'}", userId, name, contact?1:0];
    return s;
}

#pragma mark - initialization methods

- (User*)initWithJsonDictionary:(NSDictionary*)dic
{
	self = [super init];
    
    [self updateWithJSonDictionary:dic];
	
	return self;
}


- (User*)initWithSearchResult:(NSDictionary*)dic
{
	self = [super init];
	
	userId          = [[dic objectForKey:@"from_user_id"] longLongValue];
    
    name            = [dic objectForKey:@"from_user"];
	screenName      = [dic objectForKey:@"from_user"];
	location        = @"";
	url             = @"";
    followersCount  = 0;
    profileImageUrl_s = [dic objectForKey:@"profile_image_url_s"];
    protected       = false;
    description     = @"";
    
    if ((id)name == [NSNull null]) name = @"";
    if ((id)screenName == [NSNull null]) screenName = @"";
    if ((id)profileImageUrl_s == [NSNull null]) profileImageUrl_s = @"";
    [name retain];
    [screenName retain];
    [profileImageUrl_s retain];
	
	return self;
}


- (id) initWithABContact:(ABContact *)abContact
{
    self = [super init];
	if ( self ) {
		//NSArray* emailArray = [abContact emailArray];
		//if ( emailArray != nil && [emailArray count] > 0 ) {
		//	self.name = [emailArray objectAtIndex:0];
		//}
		
        if ( [abContact firstname] && [[abContact firstname] length] > 0 ) {
            self.remark = [abContact firstname];
        }
        else if ( [abContact lastname] && [[abContact lastname] length] > 0 ) {
            self.remark = [abContact lastname];
        }
        else if ( [abContact middlename] && [[abContact middlename] length] > 0 ) {
            self.remark = [abContact middlename];
        }
        else if ( [abContact nickname] && [[abContact nickname] length] > 0 ) {
            self.remark = [abContact nickname];
        }
        
        self.screenName = self.remark;
        
		
		NSArray* phoneArray = [abContact phoneArray];
		if ( phoneArray != nil && [phoneArray count] > 0 ) {
			self.name = [phoneArray objectAtIndex:0];
			self.phone = [phoneArray objectAtIndex:0];
		}
		
		self.relation = kUserRelationFollowing;
		self.contact = YES;
		self.userId = [DBConnection createRandomNum:kPKBitNumberPerson];
        self.state = kUserStateLocal;
	}
	return self;
}

/*
 SELECT user_id, name, screen_name, location, description, url, followers_count, protected, profile_image_url_s, profile_image_url_m, profile_image_url_b, province_code, province_name, city_code, city_name, is_in_contacts, contact_name, phone_number, state, account, password, relation.relation, relation.remark FROM users WHERE user_id = ?";
 */
- (id) initWithStatement:(Statement*)stmt withRelation:(BOOL)withRelation
{
    self = [super init];
	if ( self ) {
		self.userId           = [stmt getInt64:0];
		self.name             = [stmt getString:1];
		self.screenName       = [stmt getString:2];
		self.location         = [stmt getString:3];
		self.description      = [stmt getString:4];
		self.url              = [stmt getString:5];
		self.followersCount   = [stmt getInt32:6];
		self.protected        = [stmt getInt32:7] ? true : false;
		self.profileImageUrl_s  = [stmt getString:8];
		self.profileImageUrl_m  = [stmt getString:9];
		self.profileImageUrl_b  = [stmt getString:10];
		self.provinceCode  = [stmt getString:11];
		self.provinceName  = [stmt getString:12];
		self.cityCode  = [stmt getString:13];
		self.cityName  = [stmt getString:14];
		self.contact = [stmt getInt32:15];
		self.contactName = [stmt getString:16];
		self.phone = [stmt getString:17];
        self.state = [stmt getString:18];
        self.accountFlag = [stmt getInt32:19];
        self.password = [stmt getString:20];
        self.relation = kUserRelationNone;
        
        if ( withRelation ) {
            self.relation = [stmt getString:21];
            self.remark = [stmt getString:22];
        }
	}
	
	return self;
}


+ (User*) userWithLocal
{
    User* user = [[[User alloc] init] autorelease];
    user.userId = [DBConnection createRandomNum:kUserIdLength];
    user.password = [NSString stringWithFormat:@"%lld", [DBConnection createRandomNum:6]];
    user.name = [NSString stringWithFormat:@"%lld", user.userId];
    user.relation = kUserRelationSelf;
    user.accountFlag = kUserAccountAccountCurrent;
    user.state = kUserStateLocal;
    return user;
}


+ (User*)userWithId:(sqlite_int64)userId
{
    User *user = [UserStore getUserWithId:(sqlite_int64)userId];
    if (user) return user;
    
	sqlite3* theDatabase = [DBConnection getDatabase];
    
    NSString* s = [NSString stringWithFormat:@"select %@, %@ from users u, user_relation r where u.user_id = r.user_id and u.user_id = ? and r.owner_user_id = ?", kUserSQLUser, kUserSQLUserRelation];
	char* sql = (char*) [s UTF8String];
    
    Statement *stmt = [[Statement alloc] initWithDB:theDatabase sql:sql];
    [stmt bindInt64:userId forIndex:1];
    
    long long ownerUserId = [GuaziAppDelegate getAppDelegate].user.userId;
    [stmt bindInt64:ownerUserId forIndex:2];
    
    int ret = [stmt step];
    if (ret != SQLITE_ROW) {
        [stmt release];
        return nil;
    }
    
    user = [[[User alloc] initWithStatement:stmt withRelation:YES] autorelease];

    [stmt release];
    [UserStore setUser:user];
    return user;
}


+ (User*) userwithPhone:(NSString*)phone
{
	sqlite3* theDatabase = [DBConnection getDatabase];
    
    NSString* s = [NSString stringWithFormat:@"select %@ from users u where u.phone_number = ?", kUserSQLUser, kUserSQLUserRelation];
	char* sql = (char*) [s UTF8String];
    
    Statement *stmt = [[Statement alloc] initWithDB:theDatabase sql:sql];
    [stmt bindString:phone forIndex:1];
    
    User* user = nil;
    if ( [stmt step ] == SQLITE_ROW ) {
        user = [[[User alloc] initWithStatement:stmt withRelation:YES] autorelease];
    }
    
    [stmt release];
    
    if ( !user ) return nil;
    
    sql = "select relation, remark from user_relation where owner_user_id = ? and user_id = ?";
    stmt = [[Statement alloc] initWithDB:theDatabase sql:sql];
    [stmt bindInt64:[GuaziAppDelegate getAppDelegate].user.userId forIndex:1];
    [stmt bindInt64:user.userId forIndex:2];
    
    if ( [stmt step] == SQLITE_ROW ) {
        user.relation = [stmt getString:0];
        user.remark = [stmt getString:1];
    }
    
    [stmt release];
    
    return user;
}


+ (User*)userWithJsonDictionary:(NSDictionary*)dic
{
    //User *u = [UserStore getUser:[dic objectForKey:@"screen_name"]];
    sqlite_int64 userId = [[dic objectForKey:@"id"] longLongValue];
	User *u = [UserStore getUserWithId:userId];
    if (u) {
        [u updateWithJSonDictionary:dic];
        return u;
    }
    
    u = [[[User alloc] initWithJsonDictionary:dic] autorelease];
    [UserStore setUser:u];
    return u;
}


+ (User*)userWithSearchResult:(NSDictionary*)dic
{
    User *u = [UserStore getUser:[dic objectForKey:@"from_user"]];
    if (u) return u;
    
    u = [[[User alloc] initWithSearchResult:dic] autorelease];
    [UserStore setUser:u];
    return u;    
}


- (void)updateWithJSonDictionary:(NSDictionary*)dic
{
    [name release];
    [screenName release];
    [location release];
    [description release];
    [url release];
    [profileImageUrl_s release];
    [profileImageUrl_m release];
    [profileImageUrl_b release];
	[provinceCode release];
	[provinceName release];
	[cityCode release];
	[cityName release];
	[relation release];
	[phone release];
	[contactName release];
    [remark release];
    [state release];
    //[pyLetters release];
    self.pyLetters = nil;
    self.cards = nil;
    
    userId          = [[dic objectForKey:@"id"] longLongValue];
    
    name            = [dic objectForKey:@"name"];
	screenName      = [dic objectForKey:@"screen_name"];
	location        = [dic objectForKey:@"location"];
	description     = [dic objectForKey:@"description"];
	url             = [dic objectForKey:@"url"];
    profileImageUrl_s = [dic objectForKey:@"profile_image_url_s"];
	profileImageUrl_m = [dic objectForKey:@"profile_image_url_m"];
	profileImageUrl_b = [dic objectForKey:@"profile_image_url_b"];
    
    followersCount  = ([dic objectForKey:@"followers_count"] == [NSNull null]) ? 0 : [[dic objectForKey:@"followers_count"] intValue];
    //protected       = ([dic objectForKey:@"protected"]       == [NSNull null]) ? 0 : [[dic objectForKey:@"protected"] boolValue];
    
    friendsCount    = ([dic objectForKey:@"friends_count"]   == [NSNull null]) ? 0 : [[dic objectForKey:@"friends_count"] intValue];
    statusesCount   = ([dic objectForKey:@"weibo_count"]  == [NSNull null]) ? 0 : [[dic objectForKey:@"weibo_count"] intValue];
    favoritesCount  = ([dic objectForKey:@"favourites_count"]  == [NSNull null]) ? 0 : [[dic objectForKey:@"favourites_count"] intValue];
	
	provinceCode = [dic objectForKey:@"provinceCode"];
	provinceName = [dic objectForKey:@"provinceName"];
	cityCode = [dic objectForKey:@"cityCode"];
	cityName = [dic objectForKey:@"cityName"];
	relation = [dic objectForKey:@"relation"];
	
	contact = ([dic objectForKey:@"is_in_contact"] == [NSNull null]) ? NO : [[dic objectForKey:@"is_in_contact"] boolValue];
	//phone = ([dic objectForKey:@"phone_name"] == [NSNull null]) ? @"" : [dic objectForKey:@"phone_name"];
	phone = ([dic objectForKey:@"username"] == [NSNull null]) ? @"" : [dic objectForKey:@"username"];
	contactName = ([dic objectForKey:@"contact_name"] == [NSNull null]) ? @"" : [dic objectForKey:@"contact_name"];
    remark = ([dic objectForKey:@"remark"]==[NSNull null] ? @"" : [dic objectForKey:@"remark"]);
    state = ([dic objectForKey:@"state"]==[NSNull null] ? kUserStateValid : [dic objectForKey:@"state"]);
    
    self.status = nil;
 	NSDictionary* statusDic = [dic objectForKey:@"status"];
	if ( statusDic != nil && [statusDic isKindOfClass:[NSDictionary class]]) {
		status = [[Status alloc] initWithJsonDictionary:statusDic type:TWEET_TYPE_FRIENDS];
	}
    
    if ( status == nil ) {
		NSDictionary* statusDic = [dic objectForKey:@"lastest_weibo"];
		if ( statusDic != nil && [statusDic isKindOfClass:[NSDictionary class]]) {
			status = [[Status alloc] initWithJsonDictionary:statusDic type:TWEET_TYPE_FRIENDS];
		}
	}
    
    if ( status == nil ) {
		NSDictionary* statusDic = [dic objectForKey:@"retweet_status"];
		if ( statusDic != nil && [statusDic isKindOfClass:[NSDictionary class]]) {
			status = [[Status alloc] initWithJsonDictionary:statusDic type:TWEET_TYPE_FRIENDS];
		}
    }
	
    id i = [dic objectForKey:@"cards"];
    if ( i && i!=[NSNull null] && [i isKindOfClass:[NSArray class]]) {
        NSArray* arr = (NSArray*) i;
        NSMutableArray* friendCards = [NSMutableArray array];
        for ( id i2 in arr ) {
            if ( i2 == nil || i2 == [NSNull null] ) continue;
            if ( ![i2 isKindOfClass:[NSDictionary class]] ) continue;
            NSDictionary* cardDic = (NSDictionary*)i2;
            Card* card = [Card cardWithJsonDictionary:cardDic];
            card.userId = userId;
            [friendCards addObject:card];
        }
        self.cards = friendCards;
    }

    if ((id)name == [NSNull null]) name = @"";
    if ((id)screenName == [NSNull null]) screenName = @"";
    if ((id)location == [NSNull null]) location = @"";
    if ((id)description == [NSNull null]) description = @"";
    if ((id)url == [NSNull null]) url = @"";
    if ((id)profileImageUrl_b == [NSNull null]) profileImageUrl_b = @"";
    if ((id)profileImageUrl_m == [NSNull null]) profileImageUrl_m = @"";
    if ((id)profileImageUrl_s == [NSNull null]) profileImageUrl_s = @"";
    if ((id)provinceCode == [NSNull null]) provinceCode = @"";
    if ((id)provinceName == [NSNull null]) provinceName = @"";
    if ((id)cityCode == [NSNull null]) cityCode = @"";
    if ((id)cityName == [NSNull null]) cityName = @"";
	
	if ((id)relation == [NSNull null]) relation = kUserRelationNone;
    
    [name retain];
    [screenName retain];
    location = [[location unescapeHTML] retain];
    description = [[description unescapeHTML] retain];
    [url retain];
    [profileImageUrl_b retain];
    [profileImageUrl_m retain];
    [profileImageUrl_s retain];
    [provinceCode retain];
    [provinceName retain];
    [cityCode retain];
    [cityName retain];
	[relation retain];
	[phone retain];
	[contactName retain];
    [remark retain];
    [state retain];
}


#pragma mark - other methods

- (void)updateDB:(BOOL)withRelation withName:(BOOL)withName withAccount:(BOOL)withAccount
{
    if ( [User isExistUser:self.userId] ) {
        [self updateUser:withRelation withName:withName withAccount:withAccount];
    }
    else {
        [self insertUser:withRelation];
    }
}


- (void) updateUser:(BOOL)withRelation withName:(BOOL)withName withAccount:(BOOL)withAccount
{
	sqlite3* theDatabase = [DBConnection getDatabase];
    
    NSString* sql = [NSString stringWithFormat:@"update users set %@ screen_name = ?, location = ?, description = ?, url = ?, followers_count = ?, protected = ?, profile_image_url_s = ?, profile_image_url_m = ?, profile_image_url_b = ?, province_code = ?, province_name = ?, city_code = ?, city_name = ?, is_in_contacts = ?, contact_name = ?, phone_number = ?, state = ? %@ where user_id = ?", 
                     withName?@"name = ?,":@"", 
                     withAccount?@",account = ?, password = ?":@""];
    
    NSLog(@"%@",sql);
    
    Statement *stmt = [[Statement alloc] initWithDB:theDatabase sql:(char*)[sql UTF8String]];
    int i = 1;
    
    if ( withName ) {
        [stmt bindString:name               forIndex:i++];
    }
    
    [stmt bindString:screenName         forIndex:i++];
    [stmt bindString:location           forIndex:i++];
    [stmt bindString:description        forIndex:i++];
    [stmt bindString:url                forIndex:i++];
    [stmt bindInt32:followersCount      forIndex:i++];
    [stmt bindInt32:protected           forIndex:i++];
    [stmt bindString:profileImageUrl_s    forIndex:i++];
    [stmt bindString:profileImageUrl_m    forIndex:i++];
    [stmt bindString:profileImageUrl_b    forIndex:i++];
	[stmt bindString:provinceCode forIndex:i++];
	[stmt bindString:provinceName forIndex:i++];
	[stmt bindString:cityCode forIndex:i++];
	[stmt bindString:cityName forIndex:i++];
	[stmt bindInt32:contact forIndex:i++];
	[stmt bindString:contactName forIndex:i++];
	[stmt bindString:phone forIndex:i++];
    [stmt bindString:state forIndex:i++];
    
    if ( withAccount ) {
        [stmt bindInt32:accountFlag forIndex:i++];
        [stmt bindString:password forIndex:i++];
    }
    
    [stmt bindInt64:userId forIndex:i++];
    
    if ([stmt step] != SQLITE_DONE) {
		[GuaziAppDelegate showAlert:@"数据库操作失败"];
        [stmt release];
        return;
    }
    
    [stmt release];
    
    if ( withRelation ) {
        [self updateRelation];
    }
}


- (void) insertUser:(BOOL)withRelation
{
	sqlite3* theDatabase = [DBConnection getDatabase];
    
    char* sql = "insert into users (user_id, name, screen_name, location, description, url, followers_count, protected, profile_image_url_s, profile_image_url_m, profile_image_url_b, province_code, province_name, city_code, city_name,  is_in_contacts, contact_name, phone_number, state, account, password) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    Statement *stmt = [[Statement alloc] initWithDB:theDatabase sql:sql];
    int i = 1;
    [stmt bindInt64:userId              forIndex:i++];
    [stmt bindString:name               forIndex:i++];
    [stmt bindString:screenName         forIndex:i++];
    [stmt bindString:location           forIndex:i++];
    [stmt bindString:description        forIndex:i++];
    [stmt bindString:url                forIndex:i++];
    [stmt bindInt32:followersCount      forIndex:i++];
    [stmt bindInt32:protected           forIndex:i++];
    [stmt bindString:profileImageUrl_s    forIndex:i++];
    [stmt bindString:profileImageUrl_m    forIndex:i++];
    [stmt bindString:profileImageUrl_b    forIndex:i++];
	[stmt bindString:provinceCode forIndex:i++];
	[stmt bindString:provinceName forIndex:i++];
	[stmt bindString:cityCode forIndex:i++];
	[stmt bindString:cityName forIndex:i++];
	[stmt bindInt32:contact forIndex:i++];
	[stmt bindString:contactName forIndex:i++];
	[stmt bindString:phone forIndex:i++];
    [stmt bindString:state forIndex:i++];
    [stmt bindInt32:accountFlag forIndex:i++];
    [stmt bindString:password forIndex:i++];
    
    if ([stmt step] != SQLITE_DONE) {
		[GuaziAppDelegate showAlert:@"数据库操作失败"];
        [stmt release];
        return;
    }
    
    [stmt release];
    
    if ( withRelation ) {
        [self updateRelation];
    }
}


- (void) updateRelation
{
    sqlite3* theDatabase = [DBConnection getDatabase];
    
    char* sql = "REPLACE INTO user_relation (user_id, owner_user_id, relation, remark) values (?,?,?,?)";
    Statement* stmt = [[Statement alloc] initWithDB:theDatabase sql:sql];
    [stmt bindInt64:userId forIndex:1];
    long long ownerId = [GuaziAppDelegate getAppDelegate].user.userId;
    [stmt bindInt64:ownerId forIndex:2];
    [stmt bindString:relation forIndex:3];
    [stmt bindString:remark forIndex:4];

    if ([stmt step] != SQLITE_DONE) {
		[GuaziAppDelegate showAlert:@"数据库操作失败"];
        [stmt release];
        return;
    }

    [stmt release];
}


+ (NSArray*) loadAllUsers
{
	sqlite3* db = [DBConnection getDatabase];
    NSString* s = [NSString stringWithFormat:@"select %@, %@ from users u , user_relation r where u.user_id = r.user_id and r.owner_user_id = ? order by u.screen_name", kUserSQLUser, kUserSQLUserRelation];
	char* sql = (char*) [s UTF8String];
	Statement* stmt = [[Statement alloc] initWithDB:db sql:sql];
    
    long long ownerId = [GuaziAppDelegate getAppDelegate].user.userId;
    [stmt bindInt64:ownerId forIndex:1];
	
	User* user = nil;
	NSMutableArray* userList = [NSMutableArray array];
	
	while ( [stmt step] == SQLITE_ROW ) {
		user = [[User alloc] initWithStatement:stmt withRelation:YES];
		[userList addObject:user];
        [user release];
	}
	
	[stmt release];
	
    [userList sortUsingFunction:sortByScreenName context:nil];
	return userList;
}


+ (NSArray*) loadUsers:(NSString*)filterName filterPhone:(NSString*)filterPhone
{
    sqlite3* db = [DBConnection getDatabase];
    NSString* sql = [NSString stringWithFormat:@"select %@, %@ from users u, user_relation r where u.user_id = r.user_id and r.owner_user_id = ? and (r.relation = '%@' or r.relation = '%@') and (u.name like ? or u.screen_name like ? or r.remark like ?) order by u.screen_name, r.remark", kUserSQLUser, kUserSQLUserRelation, kUserRelationBoth, kUserRelationFollowing];
    Statement* stmt = [[Statement alloc] initWithDB:db sql:(char*)[sql UTF8String]];
    [stmt bindInt64:[GuaziAppDelegate getAppDelegate].user.userId forIndex:1];
    
    
    NSMutableArray* array = [NSMutableArray array];
    while ( [stmt step] == SQLITE_ROW ) {
        User* user = [[User alloc] initWithStatement:stmt withRelation:YES];
        [array addObject:user];
        [user release];
    }
    
    [stmt release];
    return array;
}



+ (User*) currentAccountUser
{
	sqlite3* db = [DBConnection getDatabase];
    NSString* s = [NSString stringWithFormat:@"select %@ from users u where u.account = %d", kUserSQLUser, kUserAccountAccountCurrent];
	char* sql = (char*) [s UTF8String];
	Statement* stmt = [[Statement alloc] initWithDB:db sql:sql];
	
	User* user = nil;
	
	if ( [stmt step] == SQLITE_ROW ) {
		user = [[[User alloc] initWithStatement:stmt withRelation:YES] autorelease];
	}
	
	[stmt release];
	
	return user;
}


+ (void) updateAccountFlag:(NSInteger)flag userId:(long long)userId
{
    sqlite3* theDatabase = [DBConnection getDatabase];
    
    char* sql = "update users set account = ? where user_id = ?";
    Statement* stmt = [[Statement alloc] initWithDB:theDatabase sql:sql];
    [stmt bindInt32:flag forIndex:1];
    [stmt bindInt64:userId forIndex:2];
    
    if ([stmt step] != SQLITE_DONE) {
		[GuaziAppDelegate showAlert:@"数据库操作失败"];
        [stmt release];
        return;
    }
    
    [stmt release];
}


+ (BOOL) isExistUser:(long long)userId
{
	sqlite3* db = [DBConnection getDatabase];
    char* sql = "select count(*) from users where user_id = ?";
	Statement* stmt = [[Statement alloc] initWithDB:db sql:sql];
    [stmt bindInt64:userId forIndex:1];
	
    int i = 0;
	if ( [stmt step] == SQLITE_ROW ) {
        i = [stmt getInt32:0];
	}
	
	[stmt release];
	
	if ( i == 0 ) return NO;
    else return YES;
}


- (void)dealloc
{
    [url release];
    [location release];
    [description release];
    [name release];
    [screenName release];
    [profileImageUrl_s release];
    [profileImageUrl_m release];
    [profileImageUrl_b release];
    [provinceCode release];
    [provinceName release];
    [cityCode release];
    [cityName release];
	[relation release];
	[phone release];
	[contactName release];
    [remark release];
    [state release];
    [password release];
    [pyLetters release];
   	[super dealloc];
}

@end
